package com.lh.auth;

/**
 * @author spp
 * @date 2020-06-09 15:34
 * 自定义登陆
 **/

import com.alibaba.fastjson.JSON;
import com.lh.exception.AuthException;
import com.lh.pojo.User;
import com.lh.service.UserService;
//import com.oracle.javafx.jmx.json.JSONException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;

public class UsernamePassAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
    @Autowired
    UserService service;
    public static final String APPLICATION_JSON = "application/json";
    public static final String APPLICATION_JSON_UTF8 = "application/json;charset=UTF-8";

    AuthUserDetailsServiceImpl userDetails;
    AuthSuccessHandler authSuccessHandler;
    AuthFailHandler authFailHandler;

    public UsernamePassAuthenticationFilter() {
    }

    public UsernamePassAuthenticationFilter(AuthUserDetailsServiceImpl userDetails, AuthSuccessHandler authSuccessHandler, AuthFailHandler authFailHandler) {

        this.userDetails = userDetails;
        this.authSuccessHandler = authSuccessHandler;
        this.authFailHandler = authFailHandler;
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request,
                                                HttpServletResponse response) throws AuthenticationException {

        String contentType = request.getContentType();
        if (contentType == null) {
            throw new AuthException("内容类型不符");
        }
        if (APPLICATION_JSON.equals(contentType) || APPLICATION_JSON_UTF8.equals(contentType)) {
            UsernamePasswordAuthenticationToken authRequest;
            User user;
            try (InputStream is = request.getInputStream()) {
                int len;
                byte[] b = new byte[2048];
                StringBuilder sb = new StringBuilder();
                while ((len = is.read(b)) != -1) {
                    sb.append(new String(b, 0, len));
                }
                user = JSON.parseObject(sb.toString(), User.class);
            } catch (IOException e) {
                //将异常放到自定义的异常类中
                throw new AuthException(e.getMessage());
            }
//            catch (JSONException j){
//                throw new AuthException("参数映射错误"+j.getMessage());
//            }
            try {
                if (user != null) {
                    //获得账号、密码
                    logger.info(user);
                    //登陆逻辑
                    if ("admin".equals(user.getUsername()) && "123456".equals(user.getPassword())) {
                        authRequest = new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword());
                        setDetails(request, authRequest);
                        return getAuthenticationManager().authenticate(authRequest);
                    } else {
                        throw new AuthException("用户名密码不匹配");
                    }
                }
            } catch (Exception e) {
                throw new AuthException(e.getMessage());
            }
            return null;
        } else {
            response.setStatus(405);
            throw new AuthException("内容类型不符");
        }
    }
}
